package org.lql.algo.codecrush.hot100.slidingWindow;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: liangqinglong
 * @date: 2025-10-14 11:07
 * @description: 3. 无重复字符的最长子串 <a href="https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/?envType=study-plan-v2&envId=top-100-liked">...</a>
 **/
public class LengthOfLongestSubstring {

	public int lengthOfLongestSubstring(String s) {
		if (s == null || s.isEmpty()) {
			return 0;
		}
		// 使用HashMap来存储字符和其在当前窗口中的最后出现位置
		Map<Character, Integer> map = new HashMap<>();
		int length = 0;
		int start = 0;
		for (int i = 0; i < s.length(); i++) {
			char current = s.charAt(i);
			if (map.containsKey(current)) {
				start = Math.max(start, map.get(current) + 1);
			}
			map.put(current, i);
			length = Math.max(length, i - start + 1);
		}
		return length;
	}

	public static void main(String[] args) {
		LengthOfLongestSubstring lengthOfLongestSubstring = new LengthOfLongestSubstring();
		// 3
		System.out.println(lengthOfLongestSubstring.lengthOfLongestSubstring("abcabcbb"));
		// 1
		System.out.println(lengthOfLongestSubstring.lengthOfLongestSubstring("bbbbb"));
		// 3
		System.out.println(lengthOfLongestSubstring.lengthOfLongestSubstring("pwwkew"));
	}
}
